<?php

namespace app\api\controller;

use app\api\model\Attention;
use app\api\model\Blacklist;
use app\api\model\ConfigSystem as Config;
use app\api\model\Dymanic;
use app\api\model\Privatechat;
use app\api\model\UserDeedLimit;
use app\api\model\UserClaimAddress;
use app\api\model\YaoqingRecords;
use think\Request;
use think\Db;
use think\Validate;

class Flag extends Common {
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        // exit(json_encode(['code'=>400, 'msg'=>'该功能已永久关闭']));
    }
    /**
     * @return mixed
     */
    public function category() {
        $data = Db::name('category_of_flag')->field('id,title,require_address')->order('sort desc')->select();
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function recommend($category = 0) {
        $data = Db::name('flag_recommend')->where(['cate_id' => $category])->order('sort desc')->column('title');
        return $this->pass($data);
    }

    /**
     * @param $content
     * @param $limit_uid
     * @param $days
     * @param $startdate
     * @param $longitude
     * @param $latitude
     * @param $address
     * @param $price
     * @param $paymethod
     * @param $tip_time
     * @return mixed
     */
    public function create($content = '', $limit_uid = 0, $days = 0, $startdate = 1, $longitude = '', $latitude = '', $address = '', $price = 0, $paymethod = 0, $tip_time = '', $h5 = 0, $address_id = 0, $address_desc = '', $type = 0, $city = '', $category = '', $steps = 0, $steps_type = 0, $w2 = 0) {
        $config    = Config::where(['category' => ['in', ['flag', 'count_steps']]])->column('title, content');
        $limit_uid = $limit_uid && $limit_uid == $this->member['id'] ? 0 : $limit_uid;
        $rule      = [
            'content'    => 'require|max:60',
            'price'      => 'between:0,999999999',
            'days'       => 'require|egt:' . $config['flag_min_day'],
            'paymethod'  => 'in:2,3',
            'start_date' => 'require|in:1,2',
            'type'       => 'require|in:0,1',
            'steps_type' => 'in:0,1,2',
        ];
        $timenow   = time();
        $askfornum = 1;

        $msg = [
            'content.require'    => '邮箱格式错误',
            'content.max'        => '类目选择超出',
            'price.require'      => '价格必填',
            'price.between'      => '价格异常',
            'days.require'       => '坚持天数选择错误',
            'days.egt'           => '坚持天数不得小于 ' . $config['flag_min_day'],
            'paymethod.in'       => '支付方式错误',
            'start_date.require' => '开始日期错误',
            'start_date.in'      => '开始日期错误',
            'type.require'       => '类型选择错误',
            'type.in'            => '类型选择错误',
            'steps_type.in'      => '运动类型参数错误',
        ];
        $data = [
            'user_id'          => $this->member['id'],
            'content'          => $content,
            'price'            => $price,
            'longitude'        => $longitude,
            'latitude'         => $latitude,
            'address'          => $address,
            'limit_uid'        => $limit_uid,
            'days'             => $days,
            'start_date'       => $startdate,
            'paymethod'        => $h5 ? 2 : $paymethod,
            'tip_time'         => $tip_time,
            'create_time'      => $timenow,
            'number'           => $price > 0 ? 'flag' . uniqid() : '',
            'paystate'         => $price > 0 ? 0 : 1,
            'claim_address_id' => $address_id,
            'address_desc'     => $address_desc,
            'type'             => $type,
            'category'         => $category,
            'askfornum'        => $askfornum,
            'steps'            => $steps,
            'steps_type'       => $steps_type,
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        }
        if ($price && $price < 1) {
            return $this->miss('最低金额为1元');
        }
        if ($steps > 0) {
            if ($steps_type == 0 && $steps < $config['count_steps_flag_steps_min']) {
                return $this->miss('最小步数为 ' . $config['count_steps_flag_steps_min']);
            } elseif ($steps_type == 1 && $steps < $config['count_steps_flag_distance_min']) {
                return $this->miss('最小距离为 ' . $config['count_steps_flag_distance_min']);
            } elseif ($steps_type == 2 && $steps < $config['count_steps_flag_calorie_min']) {
                return $this->miss('最小卡路里为 ' . $config['count_steps_flag_calorie_min']);
            }
        } elseif ($steps < 0) {
            return $this->miss('参数异常');
        }
        $limit = UserDeedLimit::check($this->member['id'], 1);
        if ($limit) {
            return $this->miss('当前已被限制发布内容');
        }
        $data['start_date'] = $startdate == 1 ? date('Y-m-d') : date('Y-m-d', $timenow + 86400);
        if ($type == 1) {
            $data['end_time'] = strtotime($data['start_date']) + 86400 - 1 + 86400 * $days;
            $data['days']     = 1;
        } else {
            $data['end_time'] = strtotime($data['start_date']) + 86400 - 1;
        }
        if ($limit_uid) {
            $user = Db::name('user')->where(['id' => $limit_uid, 'delete_time' => 0])->find();
            if (!$user) {
                return $this->miss('用户不存在');
            }
        }
        if ($tip_time && !strtotime($tip_time)) {
            return $this->miss('提醒时间异常');
        }
        if (!$address_id) {
            $data['claim_address_id'] = UserClaimAddress::FindByCreate(['name' => $address, 'address' => $address_desc, 'longitude' => $longitude, 'latitude' => $latitude, 'city' => $city]);
        }
        $result = Db::name('user_flag')->insertGetId($data);
        if ($result) {
            $data['id'] = $result;
            $actions = ['api/Alipay/tradeAppPay', 'api/Wechat/app'];
            if ($price > 0) {
                if ($h5) {
                    return $this->pass('创建成功', 'data', ['order_sn' => $data['number'], 'url' => 'api/wap/pay']);
                } else {
                    $methods = $actions[$paymethod - 2];
                    if ($w2 && $methods == 'api/Wechat/app') {
                        $methods = 'api/Wechat2/app';
                    }
                    $data['url'] = action($methods, ['order_sn' => $data['number'], 'total_amount' => $data['price'], 'returnJson' => false]);
                }
            } else {
                if ($limit_uid) {
                    Privatechat::tip($data['user_id'], $limit_uid, "邀请你监督我完成小目标【" . $data['content'] . "】", json_encode(['id'=>$data['id'], 'content'=>$data['content']], JSON_UNESCAPED_UNICODE), 1, -2);
                }
            }
            return $this->pass('创建成功', 'data', $data);
        } else {
            return $this->miss('创建失败');
        }
    }

    /**
     * @param $page
     * @param $pagesize
     * @param $status
     * @return mixed
     */
    public function myflag($page = 1, $pagesize = 20, $status = 0, $state = 0) {
        $where = ['paystate' => 1, 'user_id' => $this->member['id']];
        if ($status) {
            $where['status'] = 0;
        } else {
            $where['status'] = $state ? $state : ['in', [-1, 1]];
        }
        $data = Db::name('user_flag')
            ->where($where)
            ->field('id,content,days,start_date,price,status,address,signday signcount,signtime todaysign,type,end_time,askfored,askfornum')
            ->order('id desc')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $signRecords  = [];
        $vipaskfornum = 0;
        if ($this->member['noble_grade'] && $this->member['noble_time'] > time()) {
            $privilege = Db::name('grade_noble')->where(['grade' => $this->member['noble_grade']])->value('privilege');
            $privilege = explode(',', $privilege);
            if (in_array(16, $privilege)) {
                $vipaskfornum++;
            }
        }
        $today = date('Y-m-d');
        foreach ($data as &$value) {
            $value['price']     = floatval($value['price']);
            $value['todaysign'] = date('Y-m-d', $value['todaysign']) == $today;
            if ($value['type']) {
                $day = ceil(($value['end_time'] + 1 - strtotime($value['start_date'])) / 86400);
                if ($day > 0) {
                    $value['day'] = $day;
                }
            }
            $value['end_time']  = date('Y-m-d H:i', $value['end_time']);

            if ($value['askfored'] == 0 && $vipaskfornum) {
                $value['askfornum']++;
            }
        }
        return $this->pass($data);
    }

    /**
     * @param $flag_id
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function records($flag_id = '', $to_user = '', $page = 1, $pagesize = 20) {
        $myuid = $this->member['id'];
        $where = ['delete_time' => 0, 'cate' => 1];
        if ($flag_id) {
            $where['flag_id'] = $flag_id;
        } elseif ($to_user) {
            $where['user_id'] = $to_user;
        }
        $data = Db::name('flags')
            ->where($where)
            ->order('id desc')
            ->field('longitude,latitude,update_time', 'filter')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $likes       = Db::name('flag_likes')->where(['user_id' => $myuid, 'flags_id' => ['in', array_column($data, 'id')]])->column('flags_id');
        $signRecords = Db::name('user_flag')->where(['id' => ['in', array_column($data, 'flag_id')]])->column('content,price,days,type', 'id');
        foreach ($data as $key => $value) {
            $data[$key]['images']      = $value['images'] ? explode(',', $value['images']) : [];
            $data[$key]['is_like']     = in_array($value['id'], $likes);
            $data[$key]['info']        = isset($signRecords[$value['flag_id']]) ? $signRecords[$value['flag_id']] : false;
            $data[$key]['user']        = _user_cache($value['user_id']);
            $data[$key]['create_time'] = _time($value['create_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $flags_id
     * @return mixed
     */
    public function like($flags_id) {
        $flags = Db::name('flags')->find($flags_id);
        if (!$flags) {
            return $this->miss('操作失败');
        }
        $flag_id  = $flags['flag_id'];
        $cachekey = 'flags_like:' . $this->member['id'] . ':' . $flags_id;
        $cache    = cache($cachekey);
        if ($cache && $cache > 3) {
            return $this->miss('操作频繁');
        } else {
            $cache = $cache ? $cache : 0;
        }
        $where = ['user_id' => $this->member['id'], 'flags_id' => $flags_id];
        $has   = Db::name('flag_likes')->where($where)->find();
        if ($has) {
            $res    = Db::name('flag_likes')->delete($has['id']);
            $option = 'setDec';
        } else {
            $where['time']    = time();
            $where['flag_id'] = $flag_id;
            $res              = Db::name('flag_likes')->insert($where);
            $option           = 'setInc';
        }
        if ($res) {
            Db::name('flags')->where(['id' => $flags_id, 'delete_time' => 0])->$option('likes');
            Db::name('user_flag')->where(['id' => $flag_id])->$option('likes');
            cache($cachekey, ++$cache, 10);
            return $this->pass('操作成功');
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $flags_id
     * @param $content
     * @return mixed
     */
    public function comment($flags_id = '', $content = '') {
        return $this->miss('暂未开放评论区');
        $flags = Db::name('flags')->find($flags_id);
        if (!$flags) {
            return $this->miss('评论失败');
        }
        $res = Db::name('flag_comments')->insert(['user_id' => $this->member['id'], 'flags_id' => $flags_id, 'content' => $content, 'time' => time(), 'flag_id' => $flags['flag_id']]);
        if ($res) {
            Db::name('flags')->where(['id' => $flags_id, 'delete_time' => 0])->setInc('comments');
            Db::name('user_flag')->where(['id' => $flags['flag_id']])->setInc('comments');
            return $this->pass('评论成功');
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $flags_id
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function comments($flags_id = 0, $page = 1, $pagesize = 20) {
        return $this->pass([]);
        $flags   = Db::name('flags')->cache(60)->find($flags_id);
        $flag_id = $flags['flag_id'];
        $data    = Db::name('flag_comments')->where(['flags_id' => $flags_id])->whereOr(['flag_id' => $flag_id])->order('time desc')->limit(($page - 1) * $pagesize, $pagesize)->select();
        foreach ($data as $key => $value) {
            $data[$key]['user'] = _user_cache($value['user_id']);
            $data[$key]['time'] = _time($value['time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $page
     * @param $pagesize
     * @param $nav
     * @param $status
     * @return mixed
     */
    public function flags($page = 1, $pagesize = 20, $nav = 1, $status = 0, $type = 0) {
        $config    = Config::where(['category' => ['in', ['kefu', 'user']]])->column('title, content');
        $blacklist = Blacklist::lists($this->member['id'], false);
        if ($blacklist && $blacklist[0]) {
            $blacklist[] = $config['id'];
        } else {
            $blacklist = [$config['id']];
        }
        $where = ['a.private' => 0, 'a.user_id' => ['not in', $blacklist], 'a.delete_time' => 0, 'c.delete_time' => 0];
        if ($nav == 1) {

        } elseif ($nav == 3) {
            $attentions         = Attention::lists($this->member['id'], 1);
            $where['a.user_id'] = ['in', $attentions];
        } elseif ($nav == 2) {
            $where['a.city'] = $this->member['city'];
        }
        if ($status || $status === '0') {
            switch ((int) $status) {
            case 2:
                $where['b.status'] = 1;
                break;
            case 3:
                $where['b.status'] = -1;
                break;
            default:
                $where['b.status'] = 0;
                break;
            }
        }
        if ($type) {
            $where['b.type'] = $type - 1;
        }
        $sex = $this->member['sex'] == '男' ? '女' : '男';
        $where['c.sex'] = $sex;
        
        // $limitdatetime = '2023-04-15 00:00:00';
        // $limittime = strtotime($limitdatetime);
        // if (strtotime($this->member['register_datetime']) >= $limittime) {
        //     $where['c.register_datetime'] = ['>=', $limitdatetime];
        // } else {
        //     $where['c.register_datetime'] = ['<', $limitdatetime];
        // }

        if (in_array($status, [2, 3])) {
            $dialTable = Db::name('flags')->order('id desc')->buildSql(); //先排序
            $data      = Db::table($dialTable . 'as a')
                ->join('user_flag b', 'a.flag_id=b.id')
                ->join('user c', 'c.id=b.user_id')
                ->where($where)
                ->field('a.*, b.likes, b.comments')
                ->order('id desc')
                ->group('flag_id')
                ->limit(($page - 1) * $pagesize, $pagesize)
                ->select();
        } else {
            $data = Db::name('flags')
                ->alias('a')
                ->join('user_flag b', 'a.flag_id=b.id')
                ->join('user c', 'c.id=b.user_id')
                ->where($where)
                ->field('a.*, b.likes, b.comments')
                ->order('id desc')
                ->limit(($page - 1) * $pagesize, $pagesize)
                ->select();
        }
        $supervise = Db::name('flag_supervise')->where(['user_id' => $this->member['id'], 'flag_id' => ['in', array_column($data, 'flag_id')]])->column('flag_id');
        $likes     = Db::name('flag_likes')->where(['user_id' => $this->member['id'], 'flags_id' => ['in', array_column($data, 'id')]])->column('flags_id');
        foreach ($data as $key => $value) {
            unset($data[$key]['longitude'], $data[$key]['latitude'], $data[$key]['private'], $data[$key]['update_time']);
            $data[$key]['images']      = $value['images'] ? explode(',', $value['images']) : [];
            $data[$key]['is_like']     = in_array($value['id'], $likes);
            $data[$key]['user']        = _user_cache($value['user_id']);
            $data[$key]['create_time'] = _time($value['create_time']);
            $data[$key]['flag']        = Db::name('user_flag')->where(['id' => $value['flag_id']])->cache(10)->field('price,days,content,status,limit_uid,type,end_time,start_date')->find();
            if ($data[$key]['flag']['type']) {
                $day = ceil(($data[$key]['flag']['end_time'] + 1 - strtotime($data[$key]['flag']['start_date'])) / 86400);
                if ($day > 0) {
                    $data[$key]['flag']['day'] = $day;
                }
            }
            $data[$key]['is_supervise'] = in_array($value['flag_id'], $supervise);
        }
        return $this->pass($data);
    }

    /**
     * @param $page
     * @param $pagesize
     * @param $nav
     * @param $status
     * @return mixed
     */
    public function flagsul($page = 1, $pagesize = 20, $nav = 1, $status = 0, $type = 0) {
        $config    = Config::where(['category' => ['in', ['kefu', 'user']]])->column('title, content');
        $blacklist = [$config['id']];
        $where     = ['a.private' => 0, 'a.user_id' => ['not in', $blacklist], 'a.delete_time' => 0];
        if ($nav != 1) {
            return $this->miss('请打开APP使用');
        }
        if ($status) {
            $where['b.status'] = 0;
        }
        if ($type) {
            $where['b.type'] = $type - 1;
        }
        $data = Db::name('flags')
            ->alias('a')
            ->join('user_flag b', 'a.flag_id=b.id')
            ->where($where)
            ->field('a.*, b.likes, b.comments')
            ->order('id desc')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $count = Db::name('flags')
            ->alias('a')
            ->join('user_flag b', 'a.flag_id=b.id')
            ->where($where)
            ->count();
        foreach ($data as $key => $value) {
            unset($data[$key]['longitude'], $data[$key]['latitude'], $data[$key]['private'], $data[$key]['update_time']);
            $data[$key]['images']      = $value['images'] ? explode(',', $value['images']) : [];
            $data[$key]['is_like']     = false;
            $data[$key]['user']        = _user_cache($value['user_id']);
            $data[$key]['create_time'] = _time($value['create_time']);
            $data[$key]['flag']        = Db::name('user_flag')->where(['id' => $value['flag_id']])->cache(10)->field('price,days,content,status,limit_uid,type,end_time,start_date')->find();
            if ($data[$key]['flag']['type']) {
                $day = ceil(($data[$key]['flag']['end_time'] + 1 - strtotime($data[$key]['flag']['start_date'])) / 86400);
                if ($day > 0) {
                    $data[$key]['flag']['day'] = $day;
                }
            }
            $data[$key]['is_supervise'] = false;
        }
        return $this->pass($data, 'data', ['count'=>$count]);
    }

    /**
     * @param $flag_id
     * @return mixed
     */
    public function supervise($flag_id) {
        $cachekey = 'flags_supervise:' . $this->member['id'] . ':' . $flag_id;
        $cache    = cache($cachekey);
        if ($cache && $cache > 3) {
            return $this->miss('操作频繁');
        } else {
            $cache = $cache ? $cache : 0;
        }
        $flag = Db::name('user_flag')->where(['id' => $flag_id, 'paystate' => 1, 'status' => 0, 'price' => ['>', 0]])->find();
        if (!$flag) {
            return $this->miss('围观失败');
        }
        if ($flag['user_id'] == $this->member['id']) {
            return $this->miss('不能围观自己的flag');
        }
        if ($flag['limit_uid'] && $flag['limit_uid'] != $this->member['id']) {
            return $this->miss('仅指定用户可围观');
        }
        $where = ['user_id' => $this->member['id'], 'flag_id' => $flag_id];
        $has   = Db::name('flag_supervise')->where($where)->find();
        if ($has) {
            $res    = Db::name('flag_supervise')->delete($has['id']);
            $option = 'setDec';
        } else {
            $copies  = 1;
            $timenow = time();
            if ($this->member['noble_grade'] && $this->member['noble_time'] > $timenow) {
                $privilege = Db::name('grade_noble')->where(['grade' => $this->member['noble_grade']])->value('privilege');
                $privilege = explode(',', $privilege);
                if (in_array(13, $privilege)) {
                    $copies = 3;
                }
            }
            $where['copies'] = $copies;
            $where['time']   = time();
            $res             = Db::name('flag_supervise')->insert($where);
            $option          = 'setInc';
        }
        if ($res) {
            Db::name('user_flag')->where(['id' => $flag_id])->$option('supervise');
            cache($cachekey, ++$cache, 10);
            return $this->pass('操作成功');
        }
        return $this->miss('操作失败');
    }

    /**
     * @param $flags_id
     * @return mixed
     */
    public function flagsInfo($flags_id, $returnJson = true) {
        $data = Db::name('flags')
            ->where(['id' => $flags_id, 'delete_time' => 0])
            ->field('longitude,latitude,private,update_time', 'filter')
            ->find();
        if (!$data) {
            return $this->miss('获取信息失败');
        }
        $data['user']        = _user_cache($data['user_id']);
        $data['create_time'] = _time($data['create_time']);
        $data['flag']        = Db::name('user_flag')->where(['id' => $data['flag_id']])->field('price,days,content,status,limit_uid,type,end_time,start_date,likes,comments')->find();
        $data['likes']       = $data['flag']['likes'];
        $data['comments']    = $data['flag']['comments'];
        if ($data['flag']['type']) {
            $day = ceil(($data['flag']['end_time'] + 1 - strtotime($data['flag']['start_date'])) / 86400);
            if ($day > 0) {
                $data['flag']['day'] = $day;
            }
        }
        $data['superviseInfo'] = Db::name('flag_supervise')->where(['user_id' => $this->member['id'], 'flag_id' => $data['flag_id']])->field('flag_id,score,state')->find();
        $data['superviseInfo'] = $data['superviseInfo'] ?? false;
        $data['images']        = $data['images'] ? explode(',', $data['images']) : [];
        $data['is_like']       = Db::name('flag_likes')->where(['user_id' => $this->member['id'], 'flags_id' => $flags_id])->count();
        $data['fed'] = -1;
        if ($data['address_id'] == 0 && $data['steps'] == 0 && $data['day'] > 0 && $data['askfor'] == 0 && $data['user_id'] != $this->member['id']) {
            $data['fed'] = 0;
            $hasfed = Db::name('flag_fed')->where(['flags_id'=>$flags_id, 'user_id'=>$this->member['id']])->find();
            if ($hasfed) {
                $data['fed'] = $hasfed['fed'];
            }
        }
        return $returnJson ? $this->pass($data) : $data;
    }

    /**
     * @param $flags_id
     * @return mixed
     */
    public function flagsInfoul($flags_id = 0) {
        $data = Db::name('flags')
            ->where(['id' => $flags_id, 'delete_time' => 0])
            ->field('longitude,latitude,private,update_time', 'filter')
            ->find();
        if (!$data) {
            return $this->miss('获取信息失败');
        }
        $data['user']        = _user_cache($data['user_id']);
        $data['create_time'] = _time($data['create_time']);
        $data['flag']        = Db::name('user_flag')->where(['id' => $data['flag_id']])->field('price,days,content,status,limit_uid,type,end_time,start_date')->find();
        if ($data['flag']['type']) {
            $day = ceil(($data['flag']['end_time'] + 1 - strtotime($data['flag']['start_date'])) / 86400);
            if ($day > 0) {
                $data['flag']['day'] = $day;
            }
        }
        $data['images'] = $data['images'] ? explode(',', $data['images']) : [];
        return $this->pass($data);
    }

    /**
     * @param $flag_id
     * @param $content
     * @param $images
     * @param $longitude
     * @param $latitude
     * @param $address
     * @param $type
     * @param $video
     * @param $cover
     * @return mixed
     */
    public function sign($flag_id, $content = '', $images = '', $longitude = '', $latitude = '', $address = '', $type = 1, $video = '', $cover = '') {
        $timenow  = time();
        $flagInfo = Db::name('user_flag')->where(['id' => $flag_id, 'user_id' => $this->member['id']])->find();
        $config   = Config::where(['category' => 'count_steps'])->column('title, content');
        if (!$flagInfo || !$flagInfo['paystate']) {
            return $this->miss('打卡失败');
        }
        if ($flagInfo['status'] != 0) {
            return $this->miss('flag已结束');
        }
        if (strtotime($flagInfo['start_date']) > $timenow) {
            return $this->miss('未到打卡时间');
        }
        $signcount = $flagInfo['signday'];
        if ($signcount >= $flagInfo['days']) {
            return $this->miss('flag异常，请联系客服');
        }
        if ($flagInfo['signtime'] > strtotime(date('Y-m-d'))) {
            return $this->miss('今日已打卡');
        }
        if ($flagInfo['longitude'] && $flagInfo['latitude']) {
            if (!$longitude || !$latitude) {
                return $this->miss('位置未获取成功');
            }
            $distance = _distance($longitude, $latitude, $flagInfo['longitude'], $flagInfo['latitude'], 0);
            if ($distance > 100) {
                return $this->miss('当前位置距离打卡位置较远');
            }
        }
        $todaySteps = 0;
        if ($flagInfo['steps']) {
            $todaySteps = Db::name('count_steps_records')->where(['user_id' => $this->member['id']])->whereTime('create_time', 'today')->find();
            if (!$todaySteps) {
                return $this->miss('今日还未运动哦~');
            } elseif ($flagInfo['steps_type'] == 0 && $flagInfo['steps'] > $todaySteps['steps']) {
                return $this->miss('今日步数还未达到要求');
            } elseif ($flagInfo['steps_type'] == 1 && $flagInfo['steps'] > $todaySteps['distance']) {
                return $this->miss('今日跑步距离还未达到要求');
            } elseif ($flagInfo['steps_type'] == 2 && $flagInfo['steps'] > $todaySteps['calorie']) {
                return $this->miss('今日消耗热量还未达到要求');
            }
        }
        $enroll = $video && !getenv('APP_OSS_VIDEO_UPLOAD') ? 1 : 0;
        $flagsInsert = [
            'user_id'     => $this->member['id'],
            'flag_id'     => $flag_id,
            'content'     => $content,
            'day'         => ++$signcount,
            'images'      => $cover ? $cover : $images,
            'longitude'   => $longitude,
            'latitude'    => $latitude,
            'address'     => $address,
            'private'     => $flagInfo['price'] > 0 ? 0 : 1,
            'create_time' => $timenow,
            'city'        => $this->member['city'],
            'cate'        => 1,
            'type'        => $video ? 2 : $type,
            'video'       => $enroll ? ($video?'http://'.getenv('APP_URL').$video:$video) : $video,
            'address_id'  => $flagInfo['claim_address_id'],
            'steps'       => $todaySteps['steps'],
            'steps'       => $flagInfo['steps_type'],
        ];
        $result = Db::name('flags')->insertGetId($flagsInsert);
        if ($result) {
            if ($flagsInsert['private'] == 0) {
                $dyinfo = Dymanic::add([
                    'userid'      => $flagsInsert['user_id'],
                    'content'     => $flagsInsert['content'],
                    'sumbImage'   => $flagsInsert['type'] == 2 ? '' : $flagsInsert['images'],
                    'masterimg'   => $flagsInsert['type'] == 2 ? '' : $flagsInsert['images'],
                    'video'       => $video,
                    'cover'       => $flagsInsert['type'] == 2 ? $flagsInsert['images'] : '',
                    'citys'       => $flagsInsert['city'],
                    'source_type' => 1,
                    'source_id'   => $result,
                    'enroll'   => $enroll,
                ]);
                if ($dyinfo && $enroll) {
                    _rabbitMqPublish('ffmpeg', [
                        'id' => $dyinfo['dy_id']
                    ]);
                }
            }
            $data = ['id' => $result, 'finish' => 0, 'score' => 0];
            if ($signcount == $flagInfo['days']) {
                Db::name('user_flag')->where(['id' => $flag_id])->update(['status' => 1, 'update_time' => $timenow, 'signtime' => $timenow, 'signday' => Db::raw('signday+1')]);
                if ($flagInfo['price']) {
                    // 返回积分
                    $data['score'] = $flagInfo['price'] * 5;
                    YaoqingRecords::index($flagInfo['user_id'], 0, $data['score'], 'Flag [ID:' . $flag_id . '] 坚持打卡成功 ', 1);
                }
                Privatechat::notice($flagInfo['user_id'], '您的Flag【' . $flagInfo['content'] . '】坚持打卡成功');
                $data['finish'] = 1;
            } else {
                Db::name('user_flag')->where(['id' => $flag_id])->update([
                    'end_time' => Db::raw('end_time+86400'),
                    'signtime' => $timenow,
                    'signday'  => Db::raw('signday+1'),
                ]);
            }
            if ($flagInfo['claim_address_id']) {
                Db::name('user_claim_address')->where(['id' => $flagInfo['claim_address_id']])->setInc('sign');
                UserClaimAddress::sendredpacket($flagInfo['claim_address_id'], $flagInfo['user_id'], 1, $result);
            }
            return $this->pass('打卡成功', 'data', $data);
        }
        return $this->miss('打卡失败');
    }

    /**
     * @param $flag_id
     * @return mixed
     */
    public function askFor($flag_id) {
        $content = '今天请假休息了哦~';
        $images  = '/disk/Dream_female.png';
        if ($this->member['sex'] == '男') {
            $images = '/disk/Dream_male.png';
        }
        $type     = 2;
        $timenow  = time();
        $flagInfo = Db::name('user_flag')->where(['id' => $flag_id, 'user_id' => $this->member['id']])->find();
        if (!$flagInfo || !$flagInfo['paystate']) {
            return $this->miss('请假失败');
        }
        if ($flagInfo['status'] != 0) {
            return $this->miss('flag已结束');
        }
        if (strtotime($flagInfo['start_date']) > $timenow) {
            return $this->miss('未到打卡时间');
        }
        $signcount = $flagInfo['signday'];
        if ($signcount >= $flagInfo['days']) {
            return $this->miss('flag异常，请联系客服');
        }
        if ($flagInfo['signtime'] > strtotime(date('Y-m-d'))) {
            return $this->miss('今日已打卡');
        }
        $askfornum = 0;
        if ($this->member['noble_grade'] && $this->member['noble_time'] > $timenow) {
            $privilege = Db::name('grade_noble')->where(['grade' => $this->member['noble_grade']])->value('privilege');
            $privilege = explode(',', $privilege);
            if (in_array(16, $privilege)) {
                $askfornum++;
            }
        }
        $vipaskfornum = 0;
        if ($askfornum && $flagInfo['askfored'] == 0) {
            $flagInfo['askfornum']++;
            $vipaskfornum = 1;
        }
        if ($flagInfo['askfornum'] <= 0) {
            return $this->miss('您没有请假条了哦~');
        }
        $flagsInsert = [
            'user_id'     => $this->member['id'],
            'flag_id'     => $flag_id,
            'content'     => $content,
            'day'         => ++$signcount,
            'images'      => $images,
            'private'     => $flagInfo['price'] > 0 ? 0 : 1,
            'create_time' => $timenow,
            'city'        => $this->member['city'],
            'cate'        => 1,
            'type'        => $type,
            'askfor'      => 1,
        ];
        $result = Db::name('flags')->insertGetId($flagsInsert);
        if ($result) {
            $update = [
                'signtime' => $timenow,
                'signday'  => Db::raw('signday+1'),
                'askfored' => Db::raw('askfored+1'),
            ];
            if (!$vipaskfornum) {
                $update['askfornum'] = Db::raw('askfornum-1');
            }
            $data = ['id' => $result, 'finish' => 0, 'score' => 0];
            if ($signcount == $flagInfo['days']) {
                $update = array_merge($update, [
                    'status'      => 1,
                    'update_time' => $timenow,
                ]);
                Db::name('user_flag')->where(['id' => $flag_id])->update($update);
                if ($flagInfo['price']) {
                    // 返回积分
                    $data['score'] = $flagInfo['price'] * 5;
                    YaoqingRecords::index($flagInfo['user_id'], 0, $data['score'], 'Flag [ID:' . $flag_id . '] 坚持打卡成功 ', 1);
                }
                Privatechat::notice($flagInfo['user_id'], '您的Flag【' . $flagInfo['content'] . '】坚持打卡成功');
                $data['finish'] = 1;
            } else {
                $update = array_merge($update, [
                    'end_time' => Db::raw('end_time+86400'),
                ]);
                Db::name('user_flag')->where(['id' => $flag_id])->update($update);
            }
            return $this->pass('请假成功', 'data', $data);
        }
        return $this->miss('请假失败');
    }

    /**
     * @param $flag_id
     * @return mixed
     */
    public function autoSign($flag_id) {
        $content = '今天运动量已达标！';
        $images  = '/disk/Fitness_female.png';
        if ($this->member['sex'] == '男') {
            $images = '/disk/Fitness_male.png';
        }
        $type        = 2;
        $timenow     = time();
        $flagInfo    = Db::name('user_flag')->where(['id' => $flag_id, 'user_id' => $this->member['id']])->find();
        $signcount   = $flagInfo['signday'];
        $flagsInsert = [
            'user_id'     => $this->member['id'],
            'flag_id'     => $flag_id,
            'content'     => $content,
            'day'         => ++$signcount,
            'images'      => $images,
            'private'     => $flagInfo['price'] > 0 ? 0 : 1,
            'create_time' => $timenow,
            'city'        => $this->member['city'],
            'cate'        => 1,
            'type'        => $type,
        ];
        $result = Db::name('flags')->insertGetId($flagsInsert);
        if ($result) {
            $data = ['id' => $result, 'finish' => 0, 'score' => 0];
            if ($signcount == $flagInfo['days']) {
                Db::name('user_flag')->where(['id' => $flag_id])->update(['status' => 1, 'update_time' => $timenow, 'signtime' => $timenow, 'signday' => Db::raw('signday+1')]);
                if ($flagInfo['price']) {
                    // 返回积分
                    $data['score'] = $flagInfo['price'] * 5;
                    YaoqingRecords::index($flagInfo['user_id'], 0, $data['score'], 'Flag [ID:' . $flag_id . '] 坚持打卡成功 ', 1);
                }
                Privatechat::notice($flagInfo['user_id'], '您的Flag【' . $flagInfo['content'] . '】坚持打卡成功');
                $data['finish'] = 1;
            } else {
                Db::name('user_flag')->where(['id' => $flag_id])->update([
                    'end_time' => Db::raw('end_time+86400'),
                    'signtime' => $timenow,
                    'signday'  => Db::raw('signday+1'),
                ]);
            }
        }
    }

    /**
     * @param $page
     * @param $pagesize
     * @return mixed
     */
    public function supervises($page = 1, $pagesize = 20) {
        $flag_ids = Db::name('flag_supervise')
            ->where(['user_id' => $this->member['id']])
            ->column('flag_id');

        $data = Db::name('flags')
            ->where(['flag_id' => ['in', $flag_ids], 'delete_time' => 0])
            ->order('id desc')
            ->field('longitude,latitude,update_time', 'filter')
            ->limit(($page - 1) * $pagesize, $pagesize)
            ->select();
        $likes       = Db::name('flag_likes')->where(['user_id' => $this->member['id'], 'flags_id' => ['in', array_column($data, 'id')]])->column('flags_id');
        $signRecords = Db::name('user_flag')->where(['id' => ['in', array_column($data, 'flag_id')]])->column('content,price,days,type', 'id');
        foreach ($data as $key => $value) {
            $data[$key]['images']      = $value['images'] ? explode(',', $value['images']) : [];
            $data[$key]['is_like']     = in_array($value['id'], $likes);
            $data[$key]['info']        = $signRecords[$value['flag_id']];
            $data[$key]['user']        = _user_cache($value['user_id']);
            $data[$key]['create_time'] = _time($value['create_time']);
        }
        return $this->pass($data);
    }

    /**
     * @param $flags_id
     * @return mixed
     */
    public function flagsdele($flags_id) {
        $result = Db::name('flags')->where([
            'id'          => $flags_id,
            'user_id'     => $this->member['id'],
            'delete_time' => 0,
        ])->update(['delete_time' => time()]);
        if ($result) {
            return $this->pass('删除成功');
        }
        return $this->miss('删除失败');
    }

    /**
     * @return mixed
     */
    public function statistics() {
        $routine = Db::name('user_flag')->where(['type' => 0, 'paystate' => 1])->count();
        $once    = Db::name('user_flag')->where(['type' => 1, 'paystate' => 1])->count();
        return $this->pass(['routine' => $routine, 'once' => $once]);
    }

    public function fed($flags_id, $status = 1)
    {
        $flags = Db::name('flags')->where(['id'=>$flags_id, 'day'=>['>', 0], 'address_id'=>0, 'steps'=>0, 'askfor'=>0])->find();
        if (!$flags) {
            return $this->miss('未找到内容或当前不支持反馈');
        }
        if ($flags['user_id'] == $this->member['id']) {
            return $this->miss('操作错误');
        }
        $is_weiguan = Db::name('flag_supervise')->where(['user_id'=>$this->member['id'], 'flag_id'=>$flags['flag_id']])->count();
        if (!$is_weiguan) {
            return $this->miss('围观后才可反馈');
        }

        $fed = Db::name('flag_fed')->where(['flags_id'=>$flags_id, 'user_id'=>$this->member['id']])->count();
        if ($fed) {
            return $this->miss('您已提交过意见');
        }
        $res = Db::name('flag_fed')->insert([
            'flags_id'  => $flags_id,
            'user_id'   => $this->member['id'],
            'fed'       => $status,
            'time'      => time()
        ]);
        if ($res) {
            return $this->pass('感谢您的意见');
        }
        return $this->miss('提交失败');
    }
}